<template>
  <div class="train-container">
    <div class="header">
      <h1 class="title">车次管理</h1>
      <p class="subtitle">车次信息管理，包括id、车次编号、车次类型、始发站、始发站拼音、出发时间、终点站、终点站拼音、到站时间、新增时间、修改时间</p>
    </div>

    <a-card class="operation-card">
      <div class="operation-bar">
        <a-space>
          <a-button type="primary" @click="handleQuery()" class="refresh-btn">
            <template #icon><reload-outlined /></template>
            刷新数据
          </a-button>
          <a-button type="primary" @click="onAdd" class="add-btn">
            <template #icon><plus-outlined /></template>
            新增车次
          </a-button>
        </a-space>
        <div class="statistics">
          <div class="stat-item">
            <dashboard-outlined />
            <span>车次总数: {{ pagination.total }}</span>
          </div>
        </div>
      </div>
    </a-card>

    <a-card class="table-card">
      <a-table
        :dataSource="trains"
        :columns="columns"
        :pagination="pagination"
        @change="handleTableChange"
        :loading="loading"
        :locale="{ emptyText: '暂无车次数据' }"
        rowKey="id"
        bordered
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'type'">
            <a-tag :color="record.type === 'Y' ? 'green' : 'orange'">
              <span v-for="item in TRAIN_TYPE_ARRAY" :key="item.code">
                <span v-if="item.code === record.type">{{item.desc}}</span>
              </span>
            </a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <a-space class="operation-buttons">
              <a-tooltip title="编辑车次信息">
                <a-button type="primary" size="small" @click="onEdit(record)" class="edit-btn">
                  <template #icon><edit-outlined /></template>
                </a-button>
              </a-tooltip>
              <a-popconfirm
                title="确定要删除此车次吗？"
                ok-text="确认"
                cancel-text="取消"
                @confirm="onDelete(record)"
              >
                <a-tooltip title="删除车次">
                  <a-button type="primary" danger size="small" class="delete-btn">
                    <template #icon><delete-outlined /></template>
                  </a-button>
                </a-tooltip>
              </a-popconfirm>
              <a-popconfirm
                  title="生成座位将删除已有记录，确认生成座位?"
                  @confirm="genSeat(record)"
                  ok-text="确认" cancel-text="取消">
                <a-tooltip title="生成座位">
                  <a-button type="primary" danger size="small" class="edit-btn">
                    <template #icon><diff-outlined /></template>
                  </a-button>
                </a-tooltip>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="visible"
      :title="train.id ? '编辑车次' : '添加新车次'"
      @ok="handleOk"
      ok-text="确认"
      cancel-text="取消"
      :width="600"
      centered
      class="train-modal"
    >
      <a-form :model="train" :label-col="{span: 6}" :wrapper-col="{ span: 16 }">
        <a-form-item label="车次编号">
          <a-input v-model:value="train.code" placeholder="请输入车次编号" allow-clear :disabled="!!train.id" />
        </a-form-item>
        <a-form-item label="车次类型">
          <a-select v-model:value="train.type" placeholder="请选择车次类型">
            <a-select-option v-for="item in TRAIN_TYPE_ARRAY" :key="item.code" :value="item.code">
              {{item.desc}}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="始发站">
          <station-select-view v-model="train.start" width="50%"></station-select-view>
        </a-form-item>
        <a-form-item label="始发站拼音">
          <a-input v-model:value="train.startPinyin" disabled placeholder="请输入始发站拼音" allow-clear />
        </a-form-item>
        <a-form-item label="出发时间">
          <a-time-picker v-model:value="train.startTime" valueFormat="HH:mm:ss" placeholder="请选择时间" style="width: 100%" />
        </a-form-item>
        <a-form-item label="终点站">
          <station-select-view v-model="train.end" width="50%"></station-select-view>
        </a-form-item>
        <a-form-item label="终点站拼音">
          <a-input v-model:value="train.endPinyin" disabled placeholder="请输入终点站拼音" allow-clear />
        </a-form-item>
        <a-form-item label="到站时间">
          <a-time-picker v-model:value="train.endTime" valueFormat="HH:mm:ss" placeholder="请选择时间" style="width: 100%" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button key="back" @click="visible = false">取消</a-button>
        <a-button key="submit" type="primary" @click="handleOk">提交</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted,watch } from 'vue';
import { notification } from "ant-design-vue";
import axios from "axios";
import {pinyin} from "pinyin-pro";
import{
  ReloadOutlined, PlusOutlined, EditOutlined,
  DeleteOutlined, DashboardOutlined,DiffOutlined
} from '@ant-design/icons-vue';
import StationSelectView from "@/components/station-select.vue";

export default defineComponent({
  name: "train-view",
  components: {
    StationSelectView,
    ReloadOutlined,DiffOutlined,
    PlusOutlined, EditOutlined, DeleteOutlined,
    DashboardOutlined
  },
  setup() {
    const TRAIN_TYPE_ARRAY = window.TRAIN_TYPE_ARRAY;
    const visible = ref(false);
    let train = ref({
      id: undefined,
      code: undefined,
      type: undefined,
      start: undefined,
      startPinyin: undefined,
      startTime: undefined,
      end: undefined,
      endPinyin: undefined,
      endTime: undefined,
      createTime: undefined,
      updateTime: undefined
    });
    const trains = ref([]);
    const pagination = ref({
      total: 0,
      current: 1,
      pageSize: 10,
    });
    let loading = ref(false);
    const columns = [
      {
        title: '车次编号',
        dataIndex: 'code',
        key: 'code',
      },
      {
        title: '车次类型',
        dataIndex: 'type',
        key: 'type',
      },
      {
        title: '始发站',
        dataIndex: 'start',
        key: 'start',
      },
      {
        title: '始发站拼音',
        dataIndex: 'startPinyin',
        key: 'startPinyin',
      },
      {
        title: '出发时间',
        dataIndex: 'startTime',
        key: 'startTime',
      },
      {
        title: '终点站',
        dataIndex: 'end',
        key: 'end',
      },
      {
        title: '终点站拼音',
        dataIndex: 'endPinyin',
        key: 'endPinyin',
      },
      {
        title: '到站时间',
        dataIndex: 'endTime',
        key: 'endTime',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        width: '150px'
      }
    ];
    watch(() => train.value.start, ()=>{
      if (Tool.isNotEmpty(train.value.start)) {
        train.value.startPinyin = pinyin(train.value.start, { toneType: 'none'}).replaceAll(" ", "");
      } else {
        train.value.startPinyin = "";
      }
    }, {immediate: true});
    watch(() => train.value.end, ()=>{
      if (Tool.isNotEmpty(train.value.end)) {
        train.value.endPinyin = pinyin(train.value.end, { toneType: 'none'}).replaceAll(" ", "");
      } else {
        train.value.endPinyin = "";
      }
    }, {immediate: true});

    const onAdd = () => {
      train.value = {};
      visible.value = true;
    };

    const onEdit = (record) => {
      train.value = window.Tool.copy(record);
      visible.value = true;
    };

    const onDelete = (record) => {
      axios.delete("/business/admin/train/delete/" + record.id).then((response) => {
        const data = response.data;
        if (data.success) {
          notification.success({
            message: '删除成功',
          });
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize,
          });
        } else {
          notification.error({description: data.message});
        }
      });
    };

    const handleOk = () => {
      axios.post("/business/admin/train/save", train.value).then((response) => {
        let data = response.data;
        if (data.success) {
          notification.success({
            message: '保存成功',
            description: train.value.id ? '车次信息已更新' : '新车次已添加',
          });
          visible.value = false;
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize
          });
        } else {
          notification.error({description: data.message});
        }
      });
    };

    const handleQuery = (param) => {
      if (!param) {
        param = {
          page: 1,
          size: pagination.value.pageSize
        };
      }
      loading.value = true;
      axios.get("/business/admin/train/query-list", {
        params: {
          page: param.page,
          size: param.size
        }
      }).then((response) => {
        loading.value = false;
        let data = response.data;
        if (data.success) {
          trains.value = data.content.list;
          pagination.value.current = param.page;
          pagination.value.total = data.content.total;
        } else {
          notification.error({description: data.message});
        }
      }).catch(() => {
        loading.value = false;
      });
    };

    const handleTableChange = (pagination) => {
      handleQuery({
        page: pagination.current,
        size: pagination.pageSize
      });
    };

    const genSeat = (record) => {
      loading.value = true;
      axios.get("/business/admin/train/gen-seat/" + record.code).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          notification.success({description: "生成成功！"});
        } else {
          notification.error({description: data.message});
        }
      });
    };
    onMounted(() => {
      handleQuery({
        page: 1,
        size: pagination.value.pageSize
      });
    });

    return {
      TRAIN_TYPE_ARRAY,
      train,
      visible,
      trains,
      pagination,
      columns,
      handleTableChange,
      handleQuery,
      loading,
      onAdd,
      handleOk,
      onEdit,
      onDelete,
      genSeat
    };
  },
});
</script>

<style scoped>
.train-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.header {
  margin-bottom: 24px;
  text-align: center;
}

.title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2f3d;
  margin-bottom: 8px;
  background: linear-gradient(90deg, #1890ff, #722ed1);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.subtitle {
  color: #606266;
  font-size: 16px;
}

.operation-card {
  margin-bottom: 24px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.table-card {
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.refresh-btn, .add-btn {
  border-radius: 6px;
  font-weight: 500;
  padding: 0 20px;
  height: 36px;
}

.add-btn {
  background: linear-gradient(90deg, #13c2c2, #1890ff);
  border: none;
}

.statistics {
  display: flex;
  gap: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #f0f9ff;
  padding: 8px 16px;
  border-radius: 6px;
  font-weight: 500;
  color: #1890ff;
}

.operation-buttons {
  display: flex;
  justify-content: center;
}

.edit-btn {
  background: linear-gradient(90deg, #52c41a, #389e0d);
  border: none;
}

.delete-btn {
  border: none;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #f0f9ff !important;
  font-weight: 600;
  color: #1f2f3d;
}

:deep(.ant-table-row) {
  transition: background-color 0.3s;
}

:deep(.ant-table-row:hover) {
  background-color: #f0f9ff !important;
}

.train-modal :deep(.ant-modal-header) {
  border-radius: 10px 10px 0 0;
}

.train-modal :deep(.ant-modal-body) {
  padding: 24px;
}

.train-modal :deep(.ant-form-item) {
  margin-bottom: 20px;
}

.train-modal :deep(.ant-input) {
  border-radius: 6px;
  height: 40px;
}

@media (max-width: 768px) {
  .operation-bar {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .train-container {
    padding: 15px;
  }

  .title {
    font-size: 24px;
  }

  .statistics {
    width: 100%;
    justify-content: flex-start;
  }
}
</style>